
package com.craterhill.java.ems.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.craterhill.java.ems.common.beans.Position;
import com.craterhill.java.ems.service.PositionService;

@Controller
public class PositionManagement {

	@Autowired
	private PositionService positionService;

	@RequestMapping(value = "/setupPositionForm.ems", method = RequestMethod.GET)
	public String setupForm(final @RequestParam(required = false, defaultValue = "0") int positionId, final ModelMap modelMap) {
		modelMap.addAttribute("positionList", positionService.getPositions());
		if(positionId != 0){
			modelMap.addAttribute("position", positionService.getPosition(positionId));
		}
		return "manage_position";
	}

	@RequestMapping(value = "/savePosition.ems", method = RequestMethod.POST)
	public String savePosition(final @ModelAttribute Position position) {
		if(position.getPositionId() == 0)
			positionService.savePosition(position);
		else
			positionService.updatePosition(position);
		return "redirect:setupPositionForm.ems";
	}

	@RequestMapping(value = "/deletePosition.ems", method = RequestMethod.GET)
	public String deletePosition(final @RequestParam int positionId) {
		positionService.deletePosition(positionId);
		return "redirect:setupPositionForm.ems";
	}

	@ModelAttribute
	public Position getPosition() {
		return new Position();
	}
}
